import java.util.ArrayList;

/**
 * Query.java This class represents a Query that travels from source to
 * destination in a can system It carries the destination point, the starting
 * node and it also keeps track of all the nodezones it has been traveling
 * through in a traceroute. This represents a distributed hashtable lookup
 * 
 * @author Praneeth Pulusani
 * 
 */
public class Query {
	// class variables
	private Point p;
	private ArrayList<Node> traceRoute;
	private Node startNode;

	/**
	 * Constructor Build or initialize the query
	 * 
	 * @param startNode
	 * @param p
	 */
	public Query(Node startNode, Point p) {
		this.p = p;
		this.startNode = startNode;
		traceRoute = new ArrayList<Node>();

	}

	/**
	 * getTraceRoute
	 * 
	 * @return list of nodes this query has been traveling through
	 */
	public ArrayList<Node> getTraceRoute() {
		return traceRoute;
	}

	/**
	 * getNumHops Dont count the first node in the number of hops because thats
	 * where it starts and makes the first hop to the second node
	 * 
	 * @return number of nodezones the query hopped
	 */
	public int getNumHops() {
		return traceRoute.size() - 1;
	}

	/**
	 * addNodeToHistory Called by a node externally when the query is passing
	 * through the node's zone. Adds the node or nodezone to the traceroute
	 * 
	 * @param n
	 */
	public void addNodeToHistory(Node n) {
		traceRoute.add(n);
	}

	/**
	 * execute called after initializing. Starts at the startnode, and gets
	 * passed through various node zones until destination is reached.
	 * 
	 * @return
	 */
	public Query execute() {
		startNode.executeQuery(this);
		return this;
	}

	/**
	 * getDestinationPoint
	 * 
	 * @return the destination point that this query is trying to reach
	 */
	public Point getDestinationPoint() {
		return p;
	}

	/**
	 * Return a printable query in a nice format
	 */
	public String toString() {
		String print = "";
		for (int h = 0; h < traceRoute.size(); h++) {
			Node hop = traceRoute.get(h);
			print += "Hop: " + h + "\tX:" + hop.getX() + "\tY:" + hop.getY()
					+ "\tZ:" + hop.getZ() + "\n";
		}
		return print;
	}
}
